import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { UserEntity } from './entities/user.entity';
import { Repository } from 'typeorm';
import { PostEntity } from 'src/post/entities/post.entity';
import { UserLikeEntity } from 'src/user-like/entities/user-like.entity';
import { UserFavoriteEntity } from 'src/user-favorite/entities/user-favorite.entity';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(UserEntity)
    private userRepository: Repository<UserEntity>,
     @InjectRepository(UserLikeEntity)
  private likeRepo: Repository<UserLikeEntity>,
  @InjectRepository(UserFavoriteEntity)
  private favRepo: Repository<UserFavoriteEntity>,
  ) {}
  async create(createUserDto: CreateUserDto) {
    console.log(createUserDto);
    const { username } = createUserDto;

    const existUser = await this.userRepository.findOne({
      where: { username },
    });

    if (existUser) {
      throw new HttpException('用户名已存在', HttpStatus.BAD_REQUEST);
    }

    const newUser = await this.userRepository.create(createUserDto);
    return await this.userRepository.save(newUser);
  }

  async findAll() {
    // throw new HttpException('错误请求', 401);
    return await this.userRepository.find();
  }

  findOne(id: number) {
    return `This action returns a #${id} user`;
  }

  async findOneByUsername(username: string) {
    return await this.userRepository.findOne({
      where: { username },
    });
  }

  async update(id: number, updateUserDto: UpdateUserDto) {
    const qb = this.userRepository.createQueryBuilder();
    return await qb.update().set(updateUserDto).where({ id }).execute();
  }

  async remove(id: number) {
    const qb = this.userRepository.createQueryBuilder();
    return await qb.delete().where({ id }).execute();
  }
  async findUserLikes(userId: number): Promise<PostEntity[]> {
  const likes = await this.likeRepo.find({ where: { user: { id: userId } }, relations: ['post'] });
  return likes.map(l => l.post);
}

async findUserFavorites(userId: number): Promise<PostEntity[]> {
  const favs = await this.favRepo.find({ where: { user: { id: userId } }, relations: ['post'] });
  return favs.map(f => f.post);
}

}
